package com.stylefeng.guns.modular.websocket;
import com.alibaba.fastjson.JSON;
import com.stylefeng.guns.core.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2017/8/19.
 */
@Component
@ServerEndpoint(value = "/webSocket",configurator=GetHttpSessionConfigurator.class)
public class WebSocket {

    //是用来记录有多少websocket有多少session在运行
    private static List<Session> sessions = new ArrayList<Session>();
    //用来记录有多少个用户使用该websocket通道
    private static List<String> userNames = new ArrayList<String>();
    //用来记录用户名和该session进行绑定
    private static Map<String,Session> map = new HashMap<String, Session>();

    private String userName;
    private CommonVO commonVO = new CommonVO();
    private final Log logger = LogFactory.getLog(this.getClass());






    @OnOpen
    public void onOpen(Session session,EndpointConfig config) {


        String params = session.getQueryString();//可以得到ws：//路径？后面的所有字符串
        System.out.println("参数："+params);
        userName = params.split("=")[1];


        sessions.add(session);
        map.put(userName,session);

        userNames.add(userName);
        commonVO.setType(1);
        commonVO.setUserNum(sessions.size());
        commonVO.setUserNames(userNames);
        commonVO.setUserName(userName);
        commonVO.setWlecome(userName+"进入了聊天室");

        this.sendMessage(JSON.toJSONString(commonVO));
        logger.info("【websocket消息】有新的连接, 总数:{}"+sessions.size());
    }


    @OnClose
    public void onClose(Session session) {
        String params = session.getQueryString();
        System.out.println("参数："+params);
        userName = params.split("=")[1];

        userNames.remove(userName);
        sessions.remove(session);
        map.remove(userName);


        commonVO.setType(2);
        commonVO.setUserNum(sessions.size());
        commonVO.setExit(userName+"离开了聊天室");
        commonVO.setUserNames(userNames);
        commonVO.setUserName(userName);

        this.sendMessage(JSON.toJSONString(commonVO));

        logger.info("【websocket消息】连接断开, 总数:{}"+sessions.size());
    }

    @OnMessage
    public void onMessage(Session session,String message) {
        MessageVO messageVO = JSON.parseObject(message,MessageVO.class);
        if (messageVO.getType()==2) {
            commonVO.setType(3);
            commonVO.setUserNum(sessions.size());
            commonVO.setMessage(messageVO.getMsg());
            commonVO.setCurrentDate(DateUtil.getTime());
            this.sendMessage(JSON.toJSONString(commonVO));
        }else if(messageVO.getType()==1){
            //单聊
            String toUsername = messageVO.getToUser();
            String fromUsername = messageVO.getFromUser();
            Session to_Session = map.get(toUsername);
            Session from_Session = map.get(fromUsername);

            commonVO.setType(4);
            commonVO.setUserName(fromUsername);
            commonVO.setMessage(messageVO.getMsg());
            commonVO.setCurrentDate(DateUtil.getTime());

            try {
                to_Session.getBasicRemote().sendText(JSON.toJSONString(commonVO));
                from_Session.getBasicRemote().sendText(JSON.toJSONString(commonVO));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }




        logger.info("【websocket消息】收到客户端发来的消息:{}"+message);
    }

    public void sendMessage(String message) {
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}